// wenshidu/addpeixun/addpeixun.js
let app = getApp()
let yuming = app.globalData.yuming
const request = require('../../config/request');
// console.log(request) 
// var getLessLimitSizeImage = require('../../config/zipPic')
// console.log(getLessLimitSizeImage)
let shuzong = []

Page({
  ...request,
  /**
   * 页面的初始数据
   */
  data: {
    yuming: yuming,
    title: '添加培训',
    photo: [],
    wuphoto: [],
    biaoti: '', //标题
    cont: '', //内容
    isxuan: false,
    isxuans: false,
    study_status: '',
    buttonClicked: false,
    cw: wx.getSystemInfoSync().windowWidth,
    zong: [],
    video: '',
  },
  // 放大
  fangda(e) {
    var img = e.currentTarget.dataset.img
    var list = e.currentTarget.dataset.list
    var arr = []
    for (let i in list) {
      arr.push(list[i]); //属性
    }
    wx.previewImage({
      current: img,
      urls: arr
    })
  },
  gofujians() {
    shuzong = this.data.zong
    console.log(shuzong)
    let that = this
    var ar = []
    ar = ['xlsx', 'xls', 'doc', 'docx', 'pdf', "jpg", "jpeg", "png"]
    wx.chooseMessageFile({
        count: 1,
        type: 'all',
        extension: ar,
        success(res) {
            console.log(res)
            // tempFilePath可以作为img标签的src属性显示图片
            var file = res.tempFiles[0].path
            var name = res.tempFiles[0].name
            console.log(file)
            var s = file.indexOf(".")
            var b = file.substring(s + 1) //下划线之后
            console.log(b)
            if (b != 'doc' && b != 'docx' && b != 'xls' && b != 'xlsx' && b != 'pdf' && b != 'jpg' && b != 'jpeg' && b != 'png') {
                wx.showToast({
                    title: '当前格式不能上传哦~',
                    icon: 'none'
                })
            } else {
                that.setData({
                    type: b
                })
                wx.uploadFile({
                    url: yuming + 'Besall/Upload',
                    filePath: file,
                    name: 'file',
                    formData: {
                        file: file
                    },
                    success(res) {
                        var data = JSON.parse(res.data)
                        var url = data.imgUrl
                        var zongurl = data.httpUrl + data.imgUrl
                        console.log(url)
                        var obj = {
                            name: name,
                            appendix_url: url,
                            zong: zongurl
                        }
                        shuzong.push(obj)
                        that.setData({
                            zong: shuzong
                        })
  
                        // that.setData({
                        //   fujian: data.imgUrl
                        // })
                        // if (code2 == 'pdf' || code2 == 'docx') {
                        // wx.downloadFile({
                        //   url: data.httpUrl + data.imgUrl,
                        //   success(res) {
                        //     var filePath = res.tempFilePath
                        //     that.setData({
                        //       fils: filePath,
                        //       zong: filePath
  
                        //     })
                        //   }
                        // })
                        // }
  
                    }
                })
            }
  
        }
    })
  },
  gojians(e) {
    let url = e.currentTarget.dataset.fil
    var that = this
    var s = url.lastIndexOf(".")
    var b = url.substring(s + 1) //下划线之后
    console.log(b)
    if (b == 'jpg' || b == 'jpeg' || b == 'png') {
        wx.previewImage({
            urls: [url]
        })
    } else {
        wx.showLoading({
            title: '正在打开中',
        })
        wx.downloadFile({
            url: url,
            success(res) {
                var filePath = res.tempFilePath
                console.log(url)
                wx.openDocument({
                    filePath: filePath,
                    fileType: b,
                    success: function (res) {
                        wx.hideLoading({
                            success: (res) => {},
                        })
                    },
                    fail(err) {
                        console.log(err)
                        wx.hideLoading({
                            success: (res) => {},
                        })
                        wx.showToast({
                            title: '打开失败',
                            icon: 'none'
                        })
                    }
                })
            },
            fail(err) {
                console.log(err)
                wx.hideLoading({
                    success: (res) => {},
                })
                wx.showToast({
                    title: '打开失败',
                    icon: 'none'
                })
            }
        })
    }


},
shanchu(e) {
  console.log(e)
  var index = e.currentTarget.dataset.index
  console.log(index)
  var zong = this.data.zong
  zong.splice(index, 1)
  this.setData({
      zong: zong
  })

},
choosevideo() {
  let that = this
  console.log("上传视频的方法")
  wx.chooseMedia({
      count: 1, //上传视频的个数
      mediaType: ['video'], //限制上传的类型为video
      sourceType: ['album', 'camera'], //视频选择来源
      maxDuration: 58, //拍摄限制时间
      // camera: 'back', //采用后置摄像头
      success: function (res) {
          wx.showLoading({
              title: '上传中',
          })
          //获取临时存放的视频资源
          let tempFilePath = res.tempFiles[0].tempFilePath
          console.log(tempFilePath)

          wx.uploadFile({
              url: yuming + 'Besall/Upload',
              filePath: tempFilePath,
              name: 'file',
              formData: {
                  file: tempFilePath
              },
              success(res) {
                  var data = JSON.parse(res.data)
                  var url = data.imgUrl
                  var zongurl = data.httpUrl + data.imgUrl
                  that.setData({
                      video: zongurl
                  })
                  wx.hideLoading({
                      success: (res) => {},
                  })
              }
          })
          // //获取该视频的播放时间
          // let duration = res.tempFiles[0].duration
          // console.log("视频播放时间为" + duration)
          // //获取视频的大小(MB单位)
          // let size = parseFloat(res.tempFiles[0].size / 1024 / 1024).toFixed(1)
          // console.log("视频大小为" + size)
          // //获取视频的高度
          // let height = res.tempFiles[0].height
          // console.log("视频高度为" + height)
          // //获取视频的宽度
          // let width = res.tempFiles[0].width
          // console.log("视频宽度为" + width)
          // //校验大小后，符合进行上传
          // if (size > 20) {
          //   let beyongSize = size - 20 //获取视频超出限制大小的数量
          //   Toast("上传的视频大小超限,超出" + beyongSize + "MB,请重新上传！")
          //   return
          // } else {
          //   //符合大小限制，进行上传
          //   console.log("开始上传！！！")
          //   that.uploadvideo({
          //     url: api.uploadfiletofastdfs, //视频上传的接口
          //     path: tempFilePath, //选取的视频资源临时地址
          //   });
          // }
      },
  })
},
spguanbs() {
  this.setData({
      video: ''
  })
},
  tijiao() {
    if (this.data.biaoti == '') {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      })
    } else if (this.data.cont == '') {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      })
    } else if (this.data.photo.length == 0) {
      wx.showToast({
        title: '请上传图片',
        icon: 'none'
      })
    } else if (this.data.study_status == '') {
      wx.showToast({
        title: '请选择分类',
        icon: 'none'
      })
    } else {
      this.jiekou()
    }
  },
  jiekou() {
    this.setData({
      buttonClicked: true
    })
    var wuphoto = this.data.wuphoto.toString()
    var zong = JSON.stringify(this.data.zong)
    this.myRequest(yuming + 'Shop/shop_training_create', {
      shopId: wx.getStorageSync('shopId'),
      study_title: this.data.biaoti,
      study_text: this.data.cont,
      study_images: wuphoto,
      study_status: this.data.study_status,
      video_url:this.data.video,
      adjunct_url:zong
    }, 'POST').then(res => {
      wx.hideLoading();
      wx.showToast({
        title: res.data.msg,
        icon: 'none'
      })
      if (res.data.code == 200) {
        setTimeout(function () {
          wx.navigateBack({
            delta: 0,
          })
        }, 1000)
      } else {
        this.setData({
          buttonClicked: false
        })
      }
    })
  },
  xuanz(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      study_status: index
    })
    if (index == 0) {
      this.setData({
        isxuan: true,
        isxuans: false,
      })
    }
    if (index == 1) {
      this.setData({
        isxuans: true,
        isxuan: false,
      })
    }
  },
  bindtit(e) {
    this.setData({
      biaoti: e.detail.value
    })
  },
  bindcont(e) {
    this.setData({
      cont: e.detail.value
    })
  },
  // 差掉
  chadiao(e) {
    var index = e.currentTarget.dataset.index
    var photo = this.data.photo;
    var wuphoto = this.data.wuphoto;
    // var dd = wuphoto.toString()
    photo.splice(index, 1)
    wuphoto.splice(index, 1)
    // dd.splice(index, 1)
    // var rr = dd.join(",")
    this.setData({
      photo: photo,
      wuphoto: wuphoto
    })
  },
  // 上传
  chuan(e) {
    var that = this
    var pics = [];
    var wuphoto = this.data.wuphoto;
    this.myChooseImage(9).then(res => {
      console.log(res)
      const tempFilePaths = res.tempFilePaths
      for (var i = 0; i < tempFilePaths.length; i++) {
        pics.push(tempFilePaths[i])
      }
      if ((pics.length) + (that.data.photo.length) > 9) {
        wx.showToast({
          title: '最多可上传' + 9 + "张",
          icon: 'none'
        })
      } else {
        for (var i = 0; i < tempFilePaths.length; i++) {
          (function (i) { // 注意这里是形参
            setTimeout(function () {
              that.duoupimg(tempFilePaths[i]).then(res => {
                wx.showLoading({
                  title: '上传图片中...',
                });
                var data = JSON.parse(res.data)
                var urls = data.httpUrl + data.imgUrl
                var wuurls = data.imgUrl
                // wuphoto = wuphoto.concat(data.imgUrl + ",")
                that.setData({
                  photo: that.data.photo.concat(urls),
                  wuphoto: that.data.wuphoto.concat(wuurls),
                });
                if (i == tempFilePaths.length - 1) {
                  wx.hideLoading();
                }
              })
            }, 800 * i); // 还是每秒执行一次，不是累加的
          })(i) // 注意这里是实参，这里把要用的参数传进去
        }
      }
    })
  },
  // 返回
  backs() {
    wx.navigateBack({
      delta: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      heights: wx.getMenuButtonBoundingClientRect().top + 5,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})